﻿using CQRS.Events;
using CQRS.Reports;
using CQRS.Sample.Domain.Events;
using CQRS.Sample.Domain.ReportDtos;

namespace CQRS.Sample.Domain.EventHandlers
{
    public class PlaneEmergencyOccuredEventHandler : IEventHandler<PlaneEmergencyOccuredEvent>
    {
        private readonly IReportingRepository _reportingRepository;

        public PlaneEmergencyOccuredEventHandler(IReportingRepository reportingRepository)
        {
            _reportingRepository = reportingRepository;
        }

        public void Execute(PlaneEmergencyOccuredEvent theEvent)
        {
            _reportingRepository.Update<PlaneDetailsReport>
                (new QueryCriteria().AddCriteria("HadEmergencies", true),
                 new QueryCriteria().AddCriteria("Id", theEvent.PlaneId));
            _reportingRepository.Update<PlaneHistoryReport>
                (new QueryCriteria().AddCriteria("HadEmergencies", true),
                 new QueryCriteria().AddCriteria("Id", theEvent.PlaneId));

            var planeEmergencyReport = new PlaneEmergencyReport(theEvent.PlaneId,
                                                        theEvent.FlightNumber, theEvent.AirportName,
                                                        theEvent.CrewCommander,
                                                        theEvent.EmergencyDate, theEvent.WeatherConditions);
            _reportingRepository.Save(planeEmergencyReport);
        }
    }
}